package com.mxt.devices.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxt.common.vo.Result;
import com.mxt.devices.entity.Devices;
import com.mxt.devices.mapper.DevicesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mxt
 * @since 2023-06-15
 */
@RestController
@CrossOrigin
@RequestMapping("/device")
public class DevicesController {
    @Autowired
    private DevicesMapper devicesMapper;


    @GetMapping
    public Result listDevices() {
        List<Devices> list = devicesMapper.selectList(null);
        return Result.success(list);
    }


    @GetMapping("/search")
    public Result selectDevice(Integer input, String value, String startDate, String endDate) {
        QueryWrapper<Devices> wrapper = new QueryWrapper<>();
        if (input != null) {
            wrapper.eq("device_id", input);
        }
        if (startDate != null && endDate != null) {
            wrapper.ge("activation_time", startDate);
            wrapper.le("activation_time", endDate);
        }
        List<Devices> list = devicesMapper.selectList(wrapper);
        return Result.success(list);
    }

    @PostMapping("/add")
    public Result addDevice(@RequestBody @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Devices device) {
        devicesMapper.insert(device);
        return Result.success();
    }

    @DeleteMapping("/delete/{deviceId}")
    public Result deleteDeviceById(@PathVariable Integer deviceId) {
        System.out.println(deviceId);
        devicesMapper.deleteById(deviceId);
        return Result.success();
    }

    @PostMapping("/update")
    public Result updateDeviceById(@RequestBody @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Devices device) {
        devicesMapper.updateById(device);
        return Result.success();
    }

    @GetMapping("/page")
    public Result getDevicePage(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
        Page<Devices> page = new Page<>(pageNum,pageSize);
        Page<Devices> devicesPage = devicesMapper.selectPage(page, null);
        List<Devices> list = devicesPage.getRecords();
        return Result.success(list);
    }

}
